<template>
  <view class="my-order-page">
    <view v-if="orderList.length === 0" class="empty-order">
      <image src="/static/empty-order.png" class="empty-img" />
      <text class="empty-text">暂无订单</text>
    </view>
    <view v-else>
      <view v-for="order in orderList" :key="order.order_id" class="order-card" @click="goOrderDetail(order)">
        <view class="order-header">
          <checkbox :checked="checkedOrderIds.includes(order.order_id)" @click.stop="toggleCheck(order.order_id)" />
          <text class="order-id">订单号：{{ order.order_id }}</text>
          <text class="order-status">{{ statusMap[order.status] }}</text>
        </view>
        <view class="order-goods-list">
          <view v-for="goods in order.goods_list" :key="goods.id" class="goods-item">
            <image :src="goods.thumb_path || goods.image || '/static/logo.png'" class="goods-img" mode="aspectFill" />
            <view class="goods-info">
              <text class="goods-title ellipsis">{{ goods.title }}</text>
              <view class="goods-meta">
                <text class="goods-count">x{{ goods.count }}</text>
                <text class="goods-price">¥{{ goods.sell_price }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="order-footer">
          <text>下单时间：{{ order.add_time || order.create_time }}</text>
          <text class="order-total">合计：¥{{ order.total_price }}</text>
        </view>
      </view>
      <!-- 底部操作栏 -->
      <view class="order-bottom-bar">
        <checkbox :checked="isAllChecked" @click="toggleAll" /> 全选
        <button class="delete-btn" :disabled="checkedOrderIds.length === 0" @click="cancelCheckedOrders">取消订单</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { request, BASE_URL } from '@/Requset/request'

const orderList = ref<any[]>([])
const checkedOrderIds = ref<string[]>([])

const statusMap = {
  0: '待支付',
  1: '已支付',
  2: '已取消'
}

onMounted(async () => {
  await fetchOrderList()
})

async function fetchOrderList() {
  const token = uni.getStorageSync('token')
  console.log('当前token:', token)
  const url = BASE_URL + 'api/userorder'
  const res = await request({
    url,
    method: 'POST',
    header: { token }
  })
  console.log('订单接口返回:', res)
  if (res.data && res.statusCode === 200) {
    if (Array.isArray(res.data)) {
      orderList.value = res.data
    } else if (Array.isArray(res.data.message)) {
      orderList.value = res.data.message
    } else {
      orderList.value = []
      console.warn('订单数据结构异常:', res.data)
    }
  }
  // 打印所有订单的状态
  orderList.value.forEach(order => {
    console.log(
      `订单id:${order.order_id}, status:${order.status}, is_cancel:${order.is_cancel}, is_finish:${order.is_finish}`
    )
  })
}

// 勾选单个订单
function toggleCheck(orderId: string) {
  const idx = checkedOrderIds.value.indexOf(orderId)
  if (idx > -1) {
    checkedOrderIds.value.splice(idx, 1)
  } else {
    checkedOrderIds.value.push(orderId)
  }
}

// 全选/取消全选
const isAllChecked = computed(() => orderList.value.length > 0 && checkedOrderIds.value.length === orderList.value.length)
function toggleAll() {
  if (isAllChecked.value) {
    checkedOrderIds.value = []
  } else {
    checkedOrderIds.value = orderList.value.map(o => o.order_id)
  }
}

// 批量取消订单
async function cancelCheckedOrders() {
  if (checkedOrderIds.value.length === 0) return
  uni.showModal({
    title: '提示',
    content: '确定要删除选中的订单吗？',
    success: async (res) => {
      if (res.confirm) {
        const token = uni.getStorageSync('token')
        for (const orderId of checkedOrderIds.value) {
          await request({
            url: BASE_URL + 'api/delorder?order_id=' + encodeURIComponent(orderId),
            method: 'POST',
            header: { token }
          })
        }
        checkedOrderIds.value = []
        uni.showToast({ title: '已删除', icon: 'none' })
        // 重新拉取订单列表，确保和后端同步
        await fetchOrderList()
      }
    }
  })
}

// 跳转到订单详情
function goOrderDetail(order) {
  uni.navigateTo({
    url: `/pages/Order_details/Order_details?order_id=${order.order_id}`
  })
}

// 登录跳转
function goLogin() {
  uni.navigateTo({
    url: `/pages/Login/Login?redirect=${encodeURIComponent(getCurrentPages().slice(-1)[0].route)}`
  })
}
</script>

<style scoped>
.my-order-page {
  padding: 24rpx;
  padding-bottom: 120rpx; /* 防止内容被底部栏遮挡 */
}
.order-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  padding: 24rpx;
}
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}
.order-id {
  font-size: 26rpx;
  color: #333;
}
.order-status {
  font-size: 24rpx;
  color: #e64340;
}
.order-goods-list {
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  padding: 12rpx 0;
  margin: 12rpx 0;
}
.goods-item {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}
.goods-img {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  margin-right: 16rpx;
  background: #f7f7f7;
}
.goods-info {
  flex: 1;
}
.goods-title {
  font-size: 26rpx;
  color: #222;
  margin-bottom: 4rpx;
}
.goods-meta {
  display: flex;
  align-items: center;
  gap: 18rpx;
}
.goods-count {
  font-size: 24rpx;
  color: #666;
  background: #e9e9e9;
  border-radius: 8px;
  padding: 0 10rpx;
}
.goods-price {
  font-size: 26rpx;
  color: #e64340;
  font-weight: bold;
}
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12rpx;
  font-size: 24rpx;
  color: #888;
}
.empty-order {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 120rpx;
}
.empty-img {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 24rpx;
}
.empty-text {
  color: #aaa;
  font-size: 28rpx;
}
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: block;
  width: 300rpx;
}
.order-bottom-bar {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border-top: 1px solid #eee;
  background: #fff;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  gap: 24rpx;
  width: 100vw;
  box-sizing: border-box;
}
.delete-btn {
  background: #e64340;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 12rpx 36rpx;
  font-size: 28rpx;
}
</style>
